package com.cbg.label.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cbg.enums.EsSearchManageExceptionEnum;
import com.cbg.label.dto.LabelInfoDTO;
import com.cbg.label.dto.LabelListDTO;
import com.cbg.label.entity.ZfwLabel;
import com.cbg.label.repository.IZfwLabelRepository;
import com.cbg.label.service.IZfwLabelService;
import com.cbg.label.vo.LabelEditVO;
import com.cbg.label.vo.LabelInfoVO;
import com.cbg.label.vo.LabelQueryVO;
import com.cbg.utils.CollectionUtils;
import com.shuyuwl.core.enums.ResultEnum;
import com.shuyuwl.core.enums.StatusEnum;
import com.shuyuwl.core.exception.SymServiceException;
import com.shuyuwl.core.vo.PageVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * 标签库，存放所有已创建的标签 serviceImpl
 *
 * @author wangjuzheng
 * @since 2019-10-16
 */
@Service
@Transactional(rollbackFor = SymServiceException.class)
public class ZfwLabelServiceImpl implements IZfwLabelService {

    @Resource
    private IZfwLabelRepository zfwLabelRepository;

    @Override
    public Page<LabelListDTO> getLabels(LabelQueryVO labelQueryVO, PageVO pageVO) {

        //状态参数验证
        Pageable pageable = PageRequest.of(pageVO.getPage().intValue() - 1, pageVO.getSize());
        Page<ZfwLabel> page = zfwLabelRepository.findAll((root, query, cb) -> {
            List<Predicate> lstPredicates = new ArrayList<>();
            //去除删除的
            lstPredicates.add(cb.notEqual(root.get("status"), StatusEnum.DELETE.getCode()));
            //根据状态
            if (labelQueryVO.getStatus() != null) {
                lstPredicates.add(cb.equal(root.get("status"), labelQueryVO.getStatus()));
            }
            //根据标签名字
            if (StringUtils.isNotBlank(labelQueryVO.getKeyWords())) {
                String keyWords = StringUtils.replace(labelQueryVO.getKeyWords(), "%", "\\%");
                lstPredicates.add(cb.like(root.get("label"), "%" + keyWords.trim() + "%"));
            }
            Predicate[] p2 = new Predicate[lstPredicates.size()];
            query.where(cb.and(lstPredicates.toArray(p2)));
            return query.getRestriction();
        }, pageable);
        List<LabelListDTO> labelListDTOS = JSONObject.parseArray(JSONObject.toJSONString(page.getContent()), LabelListDTO.class);
        return new PageImpl<>(labelListDTOS, pageable, page.getTotalElements());
    }

    @Override
    public LabelInfoDTO getLabel(Long id) {

        //获取标签信息
        ZfwLabel zfwLabel = getZfwLabel(id);

        LabelInfoDTO labelInfoDTO = new LabelInfoDTO();
        BeanUtils.copyProperties(zfwLabel, labelInfoDTO);
        return labelInfoDTO;
    }

    @Override
    public void addLabel(LabelInfoVO labelInfoVO) {

        //标签状态不存在
        if (labelInfoVO.getStatus() == null) {
            throw new SymServiceException(ResultEnum.LABEL_STATUS_ERROR);
        }
        String label = labelInfoVO.getLabel().trim();
        List<ZfwLabel> list1 = zfwLabelRepository.findByLabel(label);
        //标签名称是否存在
        if (CollectionUtils.isNotEmpty(list1)) {
            throw new SymServiceException(EsSearchManageExceptionEnum.ERROR_LABEL_NAME_NOT_NULL.getCode(), EsSearchManageExceptionEnum.ERROR_LABEL_NAME_NOT_NULL.getMsg());
        }
        ZfwLabel zfwLabel = new ZfwLabel();
        BeanUtils.copyProperties(labelInfoVO, zfwLabel);
        // --TODO
        String name = "王举正";
        //创建人
        zfwLabel.setCjr(name);
        //标签名称
        zfwLabel.setLabel(label);
        //标签的保存
        zfwLabelRepository.save(zfwLabel);

    }

    @Override
    public void updateLabel(LabelEditVO labelEditVO) {

        //标签状态不存在
        if (labelEditVO.getStatus() == null) {
            throw new SymServiceException(ResultEnum.LABEL_STATUS_ERROR);
        }
        //标签的修改
        ZfwLabel zfwLabel = getZfwLabel(labelEditVO.getId());
        //标签名称
        String label = labelEditVO.getLabel().trim();
        //标签名称是否存在
        List<ZfwLabel> list1 = zfwLabelRepository.findByLabel(label);
        if (CollectionUtils.isNotEmpty(list1)) {
            if ((list1.size() > 1 || !list1.get(0).getId().equals(zfwLabel.getId()))) {
                throw new SymServiceException(EsSearchManageExceptionEnum.ERROR_LABEL_NAME_NOT_NULL.getCode(), EsSearchManageExceptionEnum.ERROR_LABEL_NAME_NOT_NULL.getMsg());
            }
        }
        //状态（1启用 2冻结 3删除）
        zfwLabel.setStatus(labelEditVO.getStatus());
        //颜色
        zfwLabel.setColor(labelEditVO.getColor());
        //标签名称
        zfwLabel.setLabel(label);
        //备注
        zfwLabel.setMark(labelEditVO.getMark());
        //标签的保存
        zfwLabelRepository.save(zfwLabel);
    }

    @Override
    public void updateStatus(List<Long> ids, Byte status) {

        if (CollectionUtils.isNotEmpty(ids)) {
            ids.forEach(id -> {
                //获取标签信息
                ZfwLabel zfwLabel = getZfwLabel(id);
                //标签状态的修改
                zfwLabel.setStatus(status);
                zfwLabelRepository.save(zfwLabel);
            });
        }
    }

    @Override
    public void deleteLabel(List<Long> ids) {
        updateStatus(ids, StatusEnum.DELETE.getCode());
    }

    /**
     * 根据id获取标签信息
     *
     * @param id 标签id
     * @return 标签信息
     */
    private ZfwLabel getZfwLabel(Long id) {

        //标签id为空
        if (id == null) {
            throw new SymServiceException(ResultEnum.LABEL_ID_NULL_ERROR);
        }
        //获取没有删除的id信息
        ZfwLabel zfwLabel = zfwLabelRepository.getZfwLabel(id);
        //标签信息不存在
        if (zfwLabel == null) {
            throw new SymServiceException(ResultEnum.LABEL_NULL_ERROR);
        }
        return zfwLabel;
    }
}
